package com.zhiyou100.dao;

import com.zhiyou100.entity.Student;
import com.zhiyou100.mapper.StudentMapper;
import com.zhiyou100.util.mybatis.MyBatis;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author yang
 * @className StudentDao
 * @packageName com.zhiyou100.dao
 * @Description TODO 学生 dao 层 实现类
 * @date 2020-08-21 20:49
 * <p>
 * // @Repository 标志此类是持久层，会创建一个 bean
 */

@Repository
public class StudentDaoImpl implements StudentDao {
    @Override
    public List<Student> getAll() {
        try (
                SqlSession sqlSession = MyBatis.get()
                // 此代码块会自动关流（调用 close 方法），前提是类 继承或者实现了 Closeable 或者 AutoCloseable  接口
        ) {
            final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            return mapper.selectAll();
        }
    }

    @Override
    public Student getOneBySid(Integer sid) {
        try (SqlSession sqlSession = MyBatis.get()) {
            final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            return mapper.selectByPrimaryKey(sid);
        }
    }

    @Override
    public void delOneBySid(Integer sid) {
        try (SqlSession sqlSession = MyBatis.get()) {
            final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            mapper.deleteByPrimaryKey(sid);
        }
    }

    @Override
    public void addOne(Student student) {
        try (SqlSession sqlSession = MyBatis.get()) {
            final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            mapper.insertSelective(student);
        }
    }

    @Override
    public void updateOne(Student student) {
        try (SqlSession sqlSession = MyBatis.get()) {
            final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            mapper.updateByPrimaryKey(student);
        }
    }

    @Override
    public Student selectBySidAndSpwd(Integer sid, String spwd) {
        try (SqlSession sqlSession = MyBatis.get()) {
            final StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            return mapper.selectBySidAndSpwd(sid, spwd);
        }
    }

}
